<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Scholar extends SMB_Controller {
	
	public function __construct() {
		parent::__construct();
		$this->load->library('scholarship');
	}
	
	public function index() {
		$this->_get_userinfo();
		
		$this->load->helper('table');		
		$limit = $this->scholarship->count_offered_scholarship($this->userinfo['username']);
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		$params = array(
			'scholarships' => $this->scholarship->get_offered_scholarship($this->userinfo['username'], '0', $limit),
			'applystatus' => $this->session->flashdata('applystatus'),
			'pager' => get_pager(7)
		);
		$this->load->view('mahasiswa/scholarship_list', $params);
		$this->_load_common_footer();
	}
	
	public function obtained() {
		$this->_get_userinfo();
		$this->load->helper('table');
		
		$status = $this->input->post('save', TRUE);
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		
		if ($status == 'Simpan Status Penerimaan') {
			unset($_POST['save']);
			$result = $this->scholarship->update_reception_status($_POST, $this->userinfo['username']);
			$params = array(
				'scholarships' => $this->scholarship->get_obtained_scholarship($this->userinfo['username']),
				'result' => $result
			);
		} else {
			$params = array(
				'scholarships' => $this->scholarship->get_obtained_scholarship($this->userinfo['username'])
			);
		}
		
		$params['pager'] = get_pager(6);
		$this->load->view('mahasiswa/scholarship_obtained', $params);
		$this->_load_common_footer();
	}
	
	public function detail($id = NULL) {
		$this->_get_userinfo();
		$scholarship = $this->_validate_scholar_id($id, $this->userinfo['username'], TRUE);
		$this->load->library('data');
		$this->load->library('file');
		
		$documents = $this->scholarship->get_required_file($id);
		$studentfile = array();
		if ($documents != NULL) {
			foreach ($documents as $document) {
				$studentfile[$document->id] = $this->file->check_file($document->id, $this->userinfo['username']);
			}
		}
		
		$this->_load_common_header();
		$this->_load_common_navigation();
		$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
		$params = array(
			'student' => $this->data->get_student($this->userinfo['username']),
			'id' => $id,
			'documents' => $documents,
			'scholarship' => $scholarship,
			'studentfile' => $studentfile,
			'story' => $this->data->get_story($this->userinfo['username']),
			'organizations' => $this->data->get_organization($this->userinfo['username']),
			'achievements' => $this->data->get_achievement($this->userinfo['username']),
			'downloadstatus' => $this->session->flashdata('downloadstatus'),
			'nofoundfile' => $this->session->flashdata('nofoundfile')
		);
		$this->load->view('mahasiswa/scholarship_detail', $params);
		$this->_load_common_footer();
	}
	
	public function applyphoto($id = NULL) {
		$this->_get_userinfo();
		$scholarship = $this->_validate_scholar_id($id, $this->userinfo['username'], TRUE);
		$this->load->helper('download');
		$dir = 'files/applydocument/'.$id.'/'.do_hash($this->userinfo['username'], 'sha1');
		$filename = do_hash($this->userinfo['username'].'.jpg', 'sha1');
		$pathfile = $dir.'/'.$filename;
		if (file_exists($pathfile)) {
			$name = $this->userinfo['username'].'.jpg';
		} else {
			$pathfile = 'files/userphoto/'.do_hash('default.jpg', 'sha1');
			$name = 'default.jpg';
		}
		$data = file_get_contents($pathfile);
		force_download($name, $data);
	}
	
	public function applydocument($scholarid = NULL, $id = NULL) {
		$this->_get_userinfo();
		$scholarship = $this->_validate_scholar_id($scholarid, $this->userinfo['username'], TRUE);
		$document = $this->_validate_document_id($scholarid, $id, $this->userinfo['username']);
		$this->load->helper('download');
		$dir = 'files/applydocument/'.$scholarid.'/'.do_hash($this->userinfo['username'], 'sha1');
		$filename = do_hash($this->userinfo['username'].' - '.$document->name.'.pdf', 'sha1');
		$pathfile = $dir.'/'.$filename;
		var_dump($pathfile);
		if (file_exists($pathfile)) {
			$name = $this->userinfo['username'].' - '.$document->name.'.pdf';
			$data = file_get_contents($pathfile);
			force_download($name, $data);
		} else {
			$this->session->set_flashdata('downloadstatus', 'failed');
			$this->session->set_flashdata('nofoundfile', $document->name);
			redirect('mahasiswa/scholar/detail/'.$scholarid, 'location');
		}
	}
	
	public function apply($id = NULL) {
		$this->_get_userinfo();
		$scholarship = $this->_validate_scholar_id($id, $this->userinfo['username']);
		$this->load->library('data');
		$this->load->library('file');
		
		$flag_file = TRUE;
		$flag_photo = $this->_photo_check();
		$documents = $this->scholarship->get_required_file($id);
		$studentfile = array();
		if ($documents != NULL) {
			foreach ($documents as $document) {
				$studentfile[$document->id] = $this->file->check_file($document->id, $this->userinfo['username']);
				if ($studentfile[$document->id] != NULL) {
					if($this->_document_check($document->name) == FALSE) {
						$studentfile[$document->id] = NULL;
						$flag_file = FALSE;
					}
				} else {
					$flag_file = FALSE;
				}
			}
		}
		$flag_file = TRUE; // #1493 berkas tidak menjadi prasyarat daftar beasiswa
		
		$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
		if ($this->form_validation->run('apply_scholarship') == FALSE) {
			$this->_load_common_header();
			$this->_load_common_navigation();
			$this->_load_common_sidebar(get_user_sidebar($this->userinfo['role'], 'scholarship'));
			$params = array(
				'student' => $this->data->get_student($this->userinfo['username']),
				'id' => $id,
				'documents' => $documents,
				'studentfile' => $studentfile,
				'scholarship' => $scholarship,
				'story' => $this->data->get_story($this->userinfo['username']),
				'organizations' => $this->data->get_organization($this->userinfo['username']),
				'achievements' => $this->data->get_achievement($this->userinfo['username']),
				'flag_photo' => $this->_photo_check(),
				'applystatus' => $this->session->flashdata('applystatus')
			);
			$this->load->view('mahasiswa/scholarship_apply', $params);
			$this->_load_common_footer();
		} else {
			if ($flag_file == TRUE && $flag_photo == TRUE) {
				$result = $this->_do_register($id, $this->userinfo['username'], $documents);
				if ($result == TRUE) {
					$this->session->set_flashdata('applystatus', 'Pendaftaran berhasil dilakukan.');
					redirect('mahasiswa/scholar/index', 'refresh');
				} else {
					$this->session->set_flashdata('applystatus', 'Terjadi kesalahan saat pendaftaran. Silakan coba beberapa saat lagi.');
				}
			} else {
				$error = 'Terjadi kesalahan saat pendaftaran. ';
				if ($flag_file == FALSE) {
					$error = 'Terdapat dokumen yang corrupt. ';
				}
				if ($flag_photo == FALSE) {
					$error = 'File foto corrupt. ';
				}
				$this->session->set_flashdata('applystatus', $error);
				redirect('mahasiswa/scholar/apply/'.$id, 'location');
			}
		}
	}
	
	private function _do_register($id, $username, $documents) {
		$return = TRUE;
		if (is_dir('files/applydocument/'.$id) == FALSE) {
			$return = mkdir('files/applydocument/'.$id, 0775);
			if ($return == FALSE) {
				return FALSE;
			}
		}
		$dir = 'files/applydocument/'.$id.'/'.do_hash($username, 'sha1');
		if (is_dir($dir) == FALSE) {
			$return = mkdir($dir);
			if ($return == FALSE) {
				return FALSE;
			}
		}
		$filename = do_hash($this->userinfo['username'].'.jpg', 'sha1');
		$src = 'files/userphoto/'.$filename;
		$dest = $dir.'/'.$filename;
		if (file_exists($src) == TRUE) {
			if (copy($src, $dest) == FALSE) {
				return FALSE;
			}
		}
		foreach ($documents as $document) {
			$filename = do_hash($username.' - '.$document->name.'.pdf', 'sha1');
			$src = 'files/studentdocument/'.$filename;
			$dest = $dir.'/'.$filename;
			if (file_exists($src)) {
				copy($src, $dest);
			}
			/* #1493
			if (copy($src, $dest) == FALSE) {
				return FALSE;
			}
			*/
		}
		return $this->scholarship->apply_scholarship($id, $username);
	}
	
	private function _document_check($name) {
		$this->_get_userinfo();
		$filename = do_hash($this->userinfo['username'].' - '.$name.'.pdf', 'sha1');
		$pathfile = 'files/studentdocument/'.$filename;
		if (file_exists($pathfile)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	private function _photo_check() {
		$this->_get_userinfo();
		$filename = do_hash($this->userinfo['username'].'.jpg', 'sha1');
		$pathfile = 'files/userphoto/'.$filename;
		if (file_exists($pathfile)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	public function _agreement_check($str) {
		if ($str == 'Setuju') {
			return TRUE;
		} else {
			$this->form_validation->set_message('_agreement_check', 'Anda harus menyetujui prasyarat ini.');
			return FALSE;
		}
	}
	
	private function _validate_scholar_id($id, $username, $registerflag = FALSE) {
		if ($id == NULL) {
			redirect('mahasiswa/scholar/index', 'location');
			exit;
		}
		if ($registerflag == FALSE) {
			$scholarship = $this->scholarship->get_scholarship_by_id_and_username($id, $username);
		} else {
			$scholarship = $this->scholarship->get_scholarship_by_id_username_and_status($id, $username);
		}
		if ($scholarship == NULL) {
			redirect('mahasiswa/scholar/index', 'location');
			exit;
		} else {
			return $scholarship;
		}
	}
	
	private function _validate_document_id($scholarid, $id, $username) {
		if ($scholarid == NULL || $id == NULL) {
			redirect('mahasiswa/scholar/detail', 'location');
			exit;
		}
		$document = $this->scholarship->get_document_by_scholarid_id_and_username($scholarid, $id, $username);
		if ($document == NULL) {
			redirect('mahasiswa/scholar/detail', 'location');
			exit;
		}
		return $document;
	}
}